/**
 * 功能:新浪微博的身份验证,基于OAuth 1.0
 * 创建日期: 2012-03-16
 * 创建人: 全轩
 * 功能修正说明:
 * 		
 */

if(!this.SinaAuth)
{
	this.SinaAuth = {};
}

(function(){
	
	SinaAuth.appKey = '1900023088'; //appkey
	SinaAuth.appSecrt= '3f22f59ab5dbaf9531818ad676c96df5';
	SinaAuth.requestToken= '';
	SinaAuth.requestTokenSecret = '';
	
	if(!SinaAuth.accessToken)
	{
		SinaAuth.accessToken = '';
	}
	if(!SinaAuth.accessTokenSecret)
	{
		SinaAuth.accessTokenSecret = '';
	}
	
	SinaAuth.verifier = '';
	SinaAuth.callback = 'http://www.baidu.com';
	SinaAuth.signatureMethod = 'HMAC-SHA1';
	SinaAuth.timestamp = 0;
	SinaAuth.version = '1.0';
	SinaAuth.currentSignature = '';
	SinaAuth.base_request_token_url = 'http://api.t.sina.com.cn/oauth/request_token';
	SinaAuth.base_authorize_url = 'http://api.t.sina.com.cn/oauth/authorize';
	SinaAuth.base_access_token_url = 'http://api.t.sina.com.cn/oauth/access_token';
	SinaAuth.httpMethod = {POST:'POST',GET:'GET'}; //请求方式
	SinaAuth.home_max_id = 0;
	SinaAuth.home_min_id = 0;
	
	if(!SinaAuth.UID)
	{
		SinaAuth.UID = ''; //当前登陆用户的uid
	}
	
	
	/**
	 * 获取随机字符串,作为随机验证参数
	 */
	SinaAuth.Nonce = function(n)
	{
		var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','u','p','q','r','s','t','u','v','w','x','y','z'];
        //生成随机数
        var result = '';
        for (var i = 0; i < n; i++) {
            var id = Math.ceil(Math.random() * 61);
            result += chars[id];
        }
        return result;
	}
	
	/**
	 * 将json数组转换为querystring
	 * @param paras [status:'哈哈',type:'1']
	 */
	SinaAuth.GeneralQueryString = function(paras)
	{
		var queryString = '';
		paras.sort(
			function(a, b) 
			{ 
				var ac = '';
				var bc = '';
				
				for(c in a){
					ac = c;
					break;
				}
				for(c in b){
					bc = c;
					break;
				}
				
				return ac > bc ? 1 : -1;
			} 
		);
		
		for(var i=0;i< paras.length;i++)
		{
			for(var key in paras[i])
			{
				if(key != 'pic')
				{
					queryString += key + '=' + encodeURIComponent(paras[i][key]) + '&';
				}
			}
		}

		if(queryString.length > 0)
		{	
			queryString = queryString.substring(0,queryString.length-1);
		}
		//Ti.API.info('queryString:'+queryString);
		return queryString;
	}
	/**
	 * 计算basestring ,计算的方法为 httpMethod + '&' + urlencode(httpRequestUrl) + '&' + 参数列表转换后的字符串
	 * @param httpMethod
	 * @param httpRequestUrl 请求地址
	 * @param paras 所有参数包括post方式中的send方法传送的参数
	 */
	SinaAuth.BaseString = function(httpMethod,httpRequestUrl,paras)
	{
		//encodeURIComponent();
		return httpMethod + '&' + encodeURIComponent(httpRequestUrl) + '&'  + encodeURIComponent(SinaAuth.GeneralQueryString(paras));
	}
	
	/**
	 * 根据相关参数按照HMAC-SHA1的算法,获取签名
	 * @param httpMethod httprequest的请求方式一半为get或者post
	 * @param httpRequestUrl 请求的基本地址,也就是?之前的baseurl地址,不携带其它参数
	 * @param paras 请求过程中需要发送的参数,不管是get还是post的参数都可以
	 */
	SinaAuth.Signature = function(httpMethod,httpRequestUrl,paras)
	{
		var baseString = SinaAuth.BaseString(httpMethod,httpRequestUrl,paras);
		var signature = b64_hmac_sha1(SinaAuth.appSecrt + '&' + SinaAuth.accessTokenSecret,baseString) + '=';
		return signature;
	}
	
	/**
	 * 获取json数组中某个指定键的参数值
	 * @param paras json数组
	 * @param key 需要获取的值对应的key
	 */
	SinaAuth.GetValueByKey = function(paras,key)
	{
		for(var i=0;i<paras.length;i++)
		{
			for(var itemkey in paras[i])
			{
				if(itemkey == key)
				{
					return paras[i][itemkey];
					break;
				}
			}
		}
	}
	
	/**
	 * 处理httprequest请求过程中的错误问题,主要用来处理口令超时
	 * @param 新浪的接口返回的错误代码为json字符串
	 */
	SinaAuth.RequestOnError = function(errorinfo)
	{
		//"{"error":"expired_token","error_code":21327,"request":"/2/statuses/home_timeline.json?access_token="
		//{"error":"invalid_access_token","error_code":21332,"request":"/2/statuses/home_timeline.json"}
		//{"error":"User requests out of rate limit!","error_code":10023,"request":"/2/statuses/home_timeline.json"}
		Ti.API.info(errorinfo);
		var result = JSON.parse(errorinfo.source.responseText);

		var status = errorinfo.status;
		if(result.error == 'expired_token' && result.error_code == 21327)
		{
			Ti.API.info('errorinfo:'+ JSON.stringify(result));
		}
		else if(result.error == 'invalid_access_token' && result.error_code == 21332)
		{
			Ti.API.info('errorinfo:'+ JSON.stringify(result));
		}
		else if(result.error=='User requests out of rate limit!' && result.error_code == 10023)
		{
			Ti.API.info('errorinfo:'+ JSON.stringify(result));
		}
		else{
			//alert(errorinfo);
			Ti.API.info('errorinfo:'+ JSON.stringify(result));
		}
	}
	
	/**
	 * HttpRequest-GET,callback为一个参数的function
	 * @param url get方式请求的url地址
	 * @param callback get方式请求完成后进行的后续处理事件
	 */
	SinaAuth.RequestGetWithParams = function(url,params,callback)
	{

		var xhr = Ti.Network.createHTTPClient();  
		
		SinaAuth.timestamp = Date.parse(new Date());
		params = params.concat(SinaAuth.BaseParams());
		var signature = SinaAuth.Signature(SinaAuth.httpMethod.GET,url,params);
		url = url + '?' + SinaAuth.GeneralQueryString(params) + '&oauth_signature=' + encodeURIComponent(signature);

		xhr.open('GET', url);  
		xhr.onload = function(e){
			
			if(typeof callback == 'function')
			{
				callback(this.responseText);
			}
		};
		xhr.onerror = function(e)
		{
			SinaAuth.RequestOnError(e);
		};
		xhr.send();

		
	}
	
	/**
	 * HttpRequest-GET,callback为一个参数的function
	 * @param url get方式请求的url地址
	 * @param callback get方式请求完成后进行的后续处理事件
	 */
	SinaAuth.RequestGet = function(url,callback)
	{

		var xhr = Ti.Network.createHTTPClient();  
		xhr.open('GET', url);  
		xhr.onload = function(e){
			
			if(typeof callback == 'function')
			{
				callback(this.responseText);
			}
		};
		xhr.onerror = function(e)
		{
			alert(e);
			SinaAuth.RequestOnError(e);
		};
		xhr.send();

		
	}
	
		/**
	 * HttpRequest-POST ,paras 为json对象,callback为一个参数的function
	 * @param post 请求对应的url地址
	 * @param paras 为post的请求参数
	 * @param callback 为请求完成后需要进行的后续处理事件
	 */
	SinaAuth.RequestWebServiceByPOST  = function (url,data,callback)
	{
		var xhr = Ti.Network.createHTTPClient();  
		xhr.open('POST', url); 
		xhr.setRequestHeader("Content-Type", "application/soap+xml")
		xhr.onload = function(e) {  

		    if(typeof callback == 'function')
			{
				callback(this.responseText);
			}
		};  
		xhr.onerror = function(e)
		{
			alert(e);
			SinaAuth.RequestOnError(e);
		};
		xhr.send(data);
	}

	/**
	 * HttpRequest-POST ,paras 为json对象,callback为一个参数的function
	 * @param post 请求对应的url地址
	 * @param paras 为post的请求参数
	 * @param callback 为请求完成后需要进行的后续处理事件
	 */
	SinaAuth.RequestPOST  = function (url,paras,callback)
	{
		var xhr = Ti.Network.createHTTPClient();  
		xhr.open('POST', url); 

		xhr.onload = function(e) {  

		    if(typeof callback == 'function')
			{
				callback(this.responseText);
			}
		};  
		xhr.onerror = function(e)
		{
			alert(e);
			SinaAuth.RequestOnError(e);
		};
		xhr.send(paras);
	}
	
	/**
	 * HttpRequest-POST ,paras 为json对象,callback为一个参数的function
	 * @param url 请求的地址
	 * @param paras 传递的参数
	 * @param pic 附件
	 * @param callback 回调函数
	 */
	SinaAuth.RequestPOSTWithPic  = function (url,paras,pic,callback)
	{
		var xhr = Ti.Network.createHTTPClient();  
		
		var tempparas =  SinaAuth.BaseParams();
		//设置时间搓
		SinaAuth.timestamp = Date.parse(new Date());
		//拼接paras
		paras = paras.concat(tempparas);
		//进行签名算法
		var oauth_signature = encodeURIComponent(SinaAuth.Signature(SinaAuth.httpMethod.POST,url,paras));
		
		//添加固定的post方式中的header 当中的Authorization参数,所偶的参数是固定的,不需要对应的图片参数参与签名
		var Authorization = 'OAuth ';
		Authorization += 'oauth_consumer_key="'+SinaAuth.appKey+'",';
		Authorization += 'oauth_signature_method="HMAC-SHA1",';
		Authorization += 'oauth_timestamp="'+SinaAuth.GetValueByKey(paras,'oauth_timestamp')+'",';
		Authorization += 'oauth_nonce="' + SinaAuth.GetValueByKey(paras,'oauth_nonce')+'",'; 
		Authorization += 'oauth_version="1.0",';
		Authorization += 'oauth_token="' +SinaAuth.accessToken+ '",';
		Authorization += 'oauth_signature="' + oauth_signature + '"';
		
		xhr.timeout = 200000;
		xhr.enableKeepAlive = true;
		
		xhr.open('POST', url); 
		
		//此方法必须在open之后,send的之前
		xhr.setRequestHeader('Authorization',Authorization);
		
		xhr.onload = function(e) {  
		    if(typeof callback == 'function')
			{
				//发送成功后进行后续事件的处理过程
				callback(this.responseText);
			}
		};  
		xhr.onsendstream = function(e){
			Ti.API.info(JSON.stringify(e));
		};
		xhr.onerror = function(e)
		{
			//错误处理
			SinaAuth.RequestOnError(e);
		};
		
		//发送参数,此处的status不需要进行urlencode,否则会出现签名失败
		xhr.send({'source':SinaAuth.appKey,'status':SinaAuth.GetValueByKey(paras,'status'),'pic':pic});
	}
	/**
	 * 准备基本参数
	 */
	SinaAuth.BaseParams = function()
	{
		var paras = [];
		
		//添加了appkey
		paras.push({'oauth_consumer_key': SinaAuth.appKey});
		
		//第一次请求request_token的时候需要callback地址,之后就不需要在带此参数了
		if(SinaAuth.requestToken && !SinaAuth.verifier && !SinaAuth.accessToken)
		{
			paras.push({'oauth_callback':SinaAuth.callback});
		}
		//签名的方法,也就是加密方法
		paras.push({'oauth_signature_method':SinaAuth.signatureMethod});
		//时间搓
		paras.push({'oauth_timestamp':SinaAuth.timestamp});
		//随机字符串
		paras.push({'oauth_nonce':SinaAuth.Nonce(6)});
		//新浪oauth版本
		paras.push({'oauth_version':SinaAuth.version});
		
		//如果已经获取到对应的accessToken,则固定参数oauth_token设置为accessToken,否则设置为requestToken
		if(SinaAuth.accessToken)
		{
			paras.push({'oauth_token':SinaAuth.accessToken});
		}
		else if(SinaAuth.requestToken)
		{
			paras.push({'oauth_token':SinaAuth.requestToken});
		}
		
		//如果验证码不为空,则添加到基本的签名算法成员参数中
		if(SinaAuth.verifier)
		{
			paras.push({'oauth_verifier':SinaAuth.verifier});
		}
		return paras;
	}
	/**
	 * 获取指定的url
	 */
	SinaAuth.GetQueryStringByName =function(url, name) {
		var result = url.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
    	if (result == null || result.length < 1) {
        	return "";
    	}
    	return result[1];
	}
	/**
	 * @param e 为webview的load事件触发时所传递的参数
	 * @param callback 获取到access_token后需要处理的相关事件
	 * 获取access_token
	 */
	SinaAuth.Access_token = function(e,callback)
	{
		var resultData = e.source.url;
		//时间搓
		SinaAuth.timestamp = Date.parse(new Date());
		
		//获取到的验证码
		SinaAuth.verifier = SinaAuth.GetQueryStringByName('&'+resultData,'oauth_verifier');
		var params = SinaAuth.BaseParams();
		var signature = SinaAuth.Signature(SinaAuth.httpMethod.GET,SinaAuth.base_request_token_url,params);
		var oauth_signature = encodeURIComponent(signature);
		var url = SinaAuth.base_access_token_url + '?' + SinaAuth.GeneralQueryString(params) + '&oauth_signature=' + oauth_signature;
		params.push({'oauth_signature':oauth_signature});
		
		//隐藏webvview
		e.source.hide();
		
		SinaAuth.RequestPOST(url,
			params,
			function(resultPostData)
			{
				SinaAuth.accessToken = SinaAuth.GetQueryStringByName('&'+resultPostData,'oauth_token');
				SinaAuth.accessTokenSecret = SinaAuth.GetQueryStringByName('&'+resultPostData,'oauth_token_secret');
				SinaAuth.UID =  SinaAuth.GetQueryStringByName('&'+resultPostData,'user_id');
				SinaAuth.verifier = null;
				
				//获取登陆的新浪用户信息
				SinaAPI.GetUserByUID(SinaAuth.UID,function(data){
	
						//记录登陆的新浪用户信息
						SinaAuth.RecordInfo(data);
						//app启动事件
						callback();
					});

			});
	}

	/**
	 * @param callback 获取request_token和request_token_secret以后需要处理的相关事件
	 * 获取request_token和request_token_secret
	 */
	SinaAuth.Request_token_url = function(callback)
	{
		var url = '';
		SinaAuth.timestamp = Date.parse(new Date());
		var params = SinaAuth.BaseParams();
		var signature = SinaAuth.Signature(SinaAuth.httpMethod.GET,SinaAuth.base_request_token_url,params);
		url = SinaAuth.base_request_token_url + '?' + SinaAuth.GeneralQueryString(params) + '&oauth_signature=' + encodeURIComponent(signature);
		SinaAuth.RequestGet(
			url,
			function(resultData)
			{
				//从url当中获取相关的参数(oauth_token)
				SinaAuth.requestToken = SinaAuth.GetQueryStringByName('&'+resultData,'oauth_token');
				
				//从url当中获取相关的参数(oauth_token_secret)
				SinaAuth.requestTokenSecret = SinaAuth.GetQueryStringByName('&'+resultData,'oauth_token_secret');
				
				//获取request_token和request_token_secret获取对应的access_token,组织对应的url
				var url2 = SinaAuth.base_authorize_url + '?oauth_token=' +  SinaAuth.requestToken + '&display=mobile&oauth_callback='+encodeURIComponent(SinaAuth.callback);
				
				//request_token和request_token_secret获取对应的access_token,给webview设置对应的url
				callback(url2);
			}
		);
	}
	
	/**
	 * app登陆界面
	 * @param callback 登陆成功后需要完成的事件
	 */
	SinaAuth.Logon = function(callback)
	{
		var win = Ti.UI.createWindow(
			{
				title:'登陆测试',
				backgroundColor : '#fff',
				backgroundImage : 'images/logon.png'
			}
		);
		
		var url = SinaAuth.Request_token_url(function(url){
			var webView = Ti.UI.createWebView({
				url:url
			});
			
			webView.addEventListener('load',function(e){
				if(e.source.url.indexOf('oauth_verifier') >= 0)
				{
					SinaAuth.Access_token(e,callback);
				}
			});
			
			win.add(webView);
		});
		
		win.open();
	}
	
	/*
	 * 记录登陆帐号信息
	 */
	SinaAuth.RecordInfo = function(data)
	{
		//准备当前登陆的信息,用于记录数据库
		data = JSON.parse(data);
		var logoninfo = {};
		logoninfo.uid = data.id; //用户uid
		logoninfo.screen_name = data.screen_name; //昵称
		logoninfo.access_token = SinaAuth.accessToken; //口令
		logoninfo.code = SinaAuth.verifier; //code
		logoninfo.access_token_gettime = new Date().toLocaleString(); //获得口令的时间
		logoninfo.last_logontime = new Date().toLocaleString(); //最后一次登陆的时间
		logoninfo.logon_count = 1; //登陆次数
		logoninfo.istimeout = 0; //口令是否已经超时
		logoninfo.isdefault = 1;
		logoninfo.access_tokensecret = SinaAuth.accessTokenSecret;

		//记录登陆信息
		DAL.Add(
		DataBase.tableNames.users_logoninfo,
		[logoninfo],
		['uid','screen_name','isdefault','istimeout','access_token','access_tokensecret','code','access_token_gettime','last_logontime','logon_count']
		);
		
	}
}())

 //SinaApp.SinaAuth = SinaAuth;
